import { createRouter, createWebHashHistory } from "vue-router";
// 导入组件
// 这是在正常的写法
// import Layout from "@/views/layout.vue"
// 懒加载方式
const Layout = () => import('@/views/layout.vue')
const Home = () => import('@/views/home/index.vue')
const Category = () => import('@/views/category/index.vue')
const Search = () => import('@/views/search/index.vue')
const Goods = () => import('@/views/goods/index.vue')
const Login = () => import('@/views/login/index.vue')
const Cart = () => import('@/views/cart/index.vue')

//1. 定义路由规则：什么是路由规则？就是是什么路径，显示什么组件
const routes = [{
  path: '/',
  component: Layout,
  children: [
    { path: '/', component: Home },
    { path: '/category/:id', component: Category },
    { path: '/search', component: Search },
    { path: '/product/:id', component: Goods },
    { path: '/cart', component: Cart }
  ]
},
{ path: '/login', component: Login }];
// 2.createRouter函数是用来创建router实例的
const router = createRouter({
  //3.history配置路由模式：hash（locaaclhost:8080/#/home）history(locaaclhost:8080/home)
  // createWebHashHistory的意思是创建hash模式的路由
  history: createWebHashHistory(),
  routes,
  // 在路由里面配置跳转页面后定位的位置
  scrollBehavior(to, from, savedPosition) {
    // 如果之前访问过某个页面
    if (savedPosition) {
      // 回退的时候就定位到之前浏览的位置
      return savedPosition
      // 如果之前没有访问过页面，那么跳转后就直接到顶部
    } else { return { top: 0 } }

  }
});

export default router;
